package wechat_service

import (
	"context"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/spf13/viper"
	"sync"
)

var globalWechat *wechat.Wechat
var redisOpts *cache.RedisOpts
var locker sync.Mutex
var redisCache *cache.Redis

func Init() {
	redisOpts = &cache.RedisOpts{
		Host:        viper.GetString("redis.default.host") + ":" + viper.GetString("redis.default.port"),
		Password:    viper.GetString("redis.default.auth"),
		Database:    viper.GetInt("redis.default.db"),
		MaxIdle:     2,
		MaxActive:   2,
		IdleTimeout: 180,
	}
	globalWechat = wechat.NewWechat()
	redisCache = cache.NewRedis(context.Background(), redisOpts)
	globalWechat.SetCache(redisCache)
}

func GetWechat() *wechat.Wechat {
	locker.Lock()
	defer locker.Unlock()
	if globalWechat != nil {
		return globalWechat
	}
	Init()
	return globalWechat
}

func GetCache() *cache.Redis {
	locker.Lock()
	defer locker.Unlock()
	if redisCache != nil {
		return redisCache
	}
	Init()
	return redisCache
}
